package org.binglan.youziyuepai.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.binglan.youziyuepai.controller.base.BasicController;
import org.binglan.youziyuepai.entity.Image;
import org.binglan.youziyuepai.service.ImageService;
import org.binglan.youziyuepai.utils.ResponseVoUtils;
import org.binglan.youziyuepai.utils.UploadUtils;
import org.binglan.youziyuepai.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 图片相关接口
 * @author: sanjin
 * @date: 2019/4/9 18:48
 */
@Api(tags = "图片业务相关接口")
@RestController
@RequestMapping("/image")
public class ImageController extends BasicController {

    @Autowired
    FastFileStorageClient storageClient;

    @Autowired
    ImageService imageService;


    /**
     * 上传文件需要将请求头标注为
     *  PostMapping(value = "/uploadImage", headers = "content-type=multipart/form-data")
     *
     * @param files
     * @return
     */
    @ApiOperation(value = "上传图片接口", notes = "需要带上token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string")
    })
    @PostMapping(value = "/uploadImage", headers = "content-type=multipart/form-data")
    public ResponseVo uploadImage(
            @ApiParam(value = "支持格式 JPG,JPEG,PNG,GIF,BMP,WBMP，支持多图片上传，单图片最小10Kb，" +
                    "多图片一共最大20M,无法用swagger2测试,请使用postman.注意小程序 wx.upload 返回值是字符串，" +
                    "不是json格式，需要使用 JSON.parse 进行转换，注意wx.upload 参数中 name 等于此处的 files")
            @RequestParam("files") MultipartFile[] files) {
        // 用户验证
        this.getUserIdByAuth();

        // 判断上传文件名是否合法
        List<UploadUtils.Image> imageList = UploadUtils.checkMultipartImageFiles(files);
        if (imageList == null || imageList.size() == 0) return ResponseVoUtils.error("上传文件失败，可以尝试单个文件上传");

        List<String> imageUrlDbPaths = new LinkedList<>();
        // 上传文件到 fastdfs 服务器
        for (UploadUtils.Image image :
                imageList) {
            StorePath storePath = storageClient.uploadFile(image.is, image.size, image.fileExtName, null);
            imageUrlDbPaths.add(storePath.getFullPath());
        }

        // 创建 数据库 Image 实体对象
        List<Image> imageObjs = imageUrlDbPaths.stream().map(url -> {
            Image image = new Image();
            image.setUrl(url);
            return image;
        }).collect(Collectors.toList());
        // 批量上传，保存到数据库
        List<Image> images = imageService.saveImageBatch(imageObjs);
        if (images == null || images.size() != imageObjs.size()) return ResponseVoUtils.error("存储图片url失败，请重新上传");

        return ResponseVoUtils.success(images);
    }
}
